#!/usr/bin/env node

require('./lib/cmdInc');

const { _: args, ...cmdOpts } = require('minimist')(process.argv.slice(2));
const { multiSelect } = require('./lib/uiUtil');
const { DomainConfig } = require('./lib/domain.config');
const { defaultValue } = require('./lib/defaultValue');
const concurrently = require('concurrently');
const { execSync } = require('child_process');
const chalk = require('chalk');
const {colors} = require('./lib/config')

// 以src 开头的领域目录
const domainList = Object.fromEntries(
  Object.entries(DomainConfig).filter(([domainName, domainPath]) => {
    return /^(src|thirdlib)/.test(domainPath);
  })
);



let ANALYZER = defaultValue(process.env.ANALYZER, false);
let MODFED = defaultValue(process.env.MODFED, true);
let HTML = defaultValue(process.env.HTML, true);

main();

async function main() {
  ANALYZER = defaultValue(cmdOpts.A, false);

  const allDomains = ['default'].concat(Object.keys(domainList));
  const inputDomains = args.length > 0 ? allDomains.filter((m) => args.includes(m)) : [];
  const useInputDomains = inputDomains.length > 0;
  const hasBuildAllOption = cmdOpts.all || cmdOpts.a;

  let domains = hasBuildAllOption ? allDomains : useInputDomains ? inputDomains : allDomains;

  if (cmdOpts.m) {
    MODFED = false;
    domains = ['default'];
  }

  if (!useInputDomains && !hasBuildAllOption && MODFED) {
    // build selected
    const selectItems = domains.map((domain) => ({ message: domain, value: domain }));
    domains = await multiSelect('请选择合适的操作', selectItems);
  }

  if (hasBuildAllOption) {
    execSync(`npx cexp`, { stdio: 'inherit' });
  }

  if(domains.length < 1) {
      console.log(chalk.red('\n[error] 领域不能为空，请指定要编译的领域\n'))
      process.exit()
  }

  concurrently(
    domains.map((domain, index) => {
      HTML = domain === 'default';
      let command = `ANALYZER=${ANALYZER} HTML=${HTML} MODFED=${MODFED} domain=${domain} NODE_OPTIONS=\"--max-old-space-size=10240\" npx cjet build`;
      command = [`echo ${command}`, command].join('\n');

      return {
        command,
        name: domain,
        prefixColor: colors[index % colors.length],
      };
    }),
    {
      raw: false,
      env: process.env,
    }
  );
}
